package com.skyjing.askit

import com.skyjing.askit.constant.RegexConstant
import java.util.regex.Pattern

object AsRegex {

    /**
     * 简单验证手机号
     */
    @JvmStatic
    fun isMobileSimple(input: CharSequence?):Boolean{
        return isMatch(
            RegexConstant.REGEX_MOBILE_SIMPLE,
            input
        )
    }

    /**
     * 精确验证手机号
     */
    @JvmStatic
    fun isMobileExact(input: CharSequence?):Boolean{
        return isMobileExact(input, null)
    }

    private fun isMobileExact(input: CharSequence?, newSegments: List<String?>?): Boolean {
        val match: Boolean = isMatch(
            RegexConstant.REGEX_MOBILE_EXACT,
            input
        )
        if (match) return true
        if (newSegments == null) return false
        if (input == null || input.length != 11) return false
        val content = input.toString()
        for (c in content.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false
            }
        }
        for (newSegment in newSegments) {
            if (content.startsWith(newSegment!!)) {
                return true
            }
        }
        return false
    }

    /**
     * 15位和18位身份证号码的正则表达式 身份证验证
     *
     * @param idCard
     * @return
     */
    @JvmStatic
    fun validateIdCard(idCard: String?): Boolean {
        return isMatch(
            RegexConstant.REGEX_ID_CARD,
            idCard
        )
    }

    /**
     *  强密码(必须包含大小写字母和数字的组合，/*不能使用特殊字符 有歧义*/，默认长度在8-10之间)
     */
    @JvmStatic
    fun passwordStrong(psw:String?,start : Int = 8, end:Int =10):Boolean{
        val regex = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{$start,$end}\$"
        return isMatch(regex, psw)
    }

    /**
     *  密码(以字母开头，只能包含字母、数字和下划线)：^[a-zA-Z]\w{5,17}$，默认长度在8-10之间)
     */
    @JvmStatic
    fun passwordBeginLetter(psw:String?,start : Int = 8, end:Int =10) : Boolean{
        val regex = "^[a-zA-Z]\\w{${start-1},${end-1}}\$"
        return isMatch(regex, psw)
    }

    /**
     * 邮箱
     */
    @JvmStatic
    fun isEmail(mail:String?):Boolean{
        return isMatch(RegexConstant.REGEX_EMAIL, mail)
    }

    /**
     * URL
     */
    @JvmStatic
    fun isUrl(url:String?):Boolean{
        return isMatch(RegexConstant.REGEX_URL, url)
    }

    /**
     *验证汉字
     */
    @JvmStatic
    fun isChz(char : String?):Boolean{
        return isMatch(RegexConstant.REGEX_CHZ, char)
    }

    /**
     * IP地址
     */
    @JvmStatic
    fun isIP(ip:String?):Boolean{
        return isMatch(RegexConstant.REGEX_IP, ip)
    }

    /**
     * 判断是否匹配正则
     * @param regex The regex.
     * @param input The input.
     * @return {@code true}: yes<br>{@code false}: no
     */
    @JvmStatic
    fun isMatch(regex: String?, input: CharSequence?): Boolean {
        return input != null && input.isNotEmpty() && Pattern.matches(
            regex, input)
    }
}